package zap

import (
	"time"

	"gitee.com/zawei/yggdrasil/pkg/utils/xcolor"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

const (
	defaultFileDir = "."

	defaultFileName = "out.log"

	defaultFileMaxSize = 500

	defaultFileMaxAge = 1

	defaultFileMaxBackup = 10
)

const (
	// defaultBufferSize sizes the buffer associated with each WriterSync.
	defaultBufferSize = 256 * 1024

	// defaultFlushInterval means the default flush interval
	defaultFlushInterval = 30 * time.Second
)

//FileConfig
type FileConfig struct {
	Dir       string
	Name      string
	MaxSize   int
	MaxBackup int
	MaxAge    int
}

//BufferConfig
type BufferConfig struct {
	BufferSize    int
	FlushInterval time.Duration
}

//Config
type Config struct {
	Level      string
	HideCaller bool
	CallerSkip int
	Encoder    string
	File       struct {
		Enable bool
		FileConfig
	}
	EncoderConfig *zapcore.EncoderConfig
}

// DebugEncodeLevel ...
func debugEncodeLevel(lv zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
	var colorize = xcolor.Red
	switch lv {
	case zapcore.DebugLevel:
		colorize = xcolor.Blue
	case zapcore.InfoLevel:
		colorize = xcolor.Green
	case zapcore.WarnLevel:
		colorize = xcolor.Yellow
	case zapcore.ErrorLevel, zap.PanicLevel, zap.DPanicLevel, zap.FatalLevel:
		colorize = xcolor.Red
	default:
	}
	enc.AppendString(colorize(lv.CapitalString()))
}

func (config *Config) Build() *Logger {
	if config.EncoderConfig == nil {
		config.EncoderConfig = &zapcore.EncoderConfig{
			TimeKey:        "ts",
			LevelKey:       "lv",
			NameKey:        "Logger",
			CallerKey:      "caller",
			MessageKey:     "msg",
			StacktraceKey:  "stack",
			LineEnding:     zapcore.DefaultLineEnding,
			EncodeLevel:    zapcore.LowercaseColorLevelEncoder,
			EncodeTime:     zapcore.RFC3339TimeEncoder,
			EncodeDuration: zapcore.SecondsDurationEncoder,
			EncodeCaller:   zapcore.ShortCallerEncoder,
		}
	}
	if config.Level == "" {
		config.Level = "debug"
	}
	return newLogger(config)
}
